package com.smartleanx.module.hrm.framework.excelUtil.handler;

import java.util.List;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddressList;

import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;

/**
 * 自定义日期单元格输入校验 Handler
 *
 * @author yanglihao
 */
public class CustomDateValidateHandler implements CellWriteHandler {

    private List<String> dateColumn;

    public CustomDateValidateHandler(List<String> dateColumn) {
        this.dateColumn = dateColumn;
    }

    @Override
    public void afterCellDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder,
        List<WriteCellData<?>> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
        if (!isHead && dateColumn.contains(head.getFieldName())) {
            setDateValidate(writeSheetHolder, cell.getRowIndex(), cell.getColumnIndex());
        }
    }

    /**
     * 设置日期格式校验
     *
     * @param writeSheetHolder ..
     * @param rowIndex 行号
     * @param columnIndex 列号
     */
    private void setDateValidate(WriteSheetHolder writeSheetHolder, int rowIndex, int columnIndex) {

        Sheet sheet = writeSheetHolder.getSheet();
        DataValidationHelper helper = sheet.getDataValidationHelper();

        // 设置下拉列表的行：首行，末行，首列，末列
        CellRangeAddressList rangeList = new CellRangeAddressList(rowIndex, 10000, columnIndex, columnIndex);

        // TODO 校验规则暂不可用

        /*
        方式一：constraint为null
        DataValidationConstraint constraint = helper.createNumericConstraint(
            // 校验格式
            DataValidationConstraint.ValidationType.DATE,
            // 校验方式
            DataValidationConstraint.OperatorType.BETWEEN,
            // 最小日期
            String.valueOf(DateUtil.getExcelDate(LocalDate.of(1901, 1, 1))),
            // 最大日期
            String.valueOf(DateUtil.getExcelDate(LocalDate.of(9999, 12, 31))));
         */

        /*
        方式二：Excel中输入2024-12-12校验不通过
        DataValidationConstraint constraint = helper.createDateConstraint(
            // 校验方式
            DataValidationConstraint.OperatorType.BETWEEN,
            // 最小日期
            "1900-01-01",
            // 最大日期
            "2050-12-31",
            // 日期格式
            "yyyy-MM-dd");
         */
        DataValidationConstraint constraint = null;

        // 设置约束
        DataValidation validation = helper.createValidation(constraint, rangeList);
        validation.setErrorStyle(DataValidation.ErrorStyle.STOP);
        validation.setShowErrorBox(true);
        validation.createErrorBox("提示", "日期格式不正确");
        sheet.addValidationData(validation);
    }
}
